import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useAuthStore } from '../store/auth';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import('../components/helloPage.vue'),
          meta: {
            index: 1,
          }
        },

        {
          path: '/about',
          name: 'about',
          component: () => import('../components/aboutView.vue'),
          meta: {
            index: 2,
          }
        },

        {
          path: '/sch',
          name: 'sch',
          component: () => import('../components/myEdu.vue'),
          meta: {
            index: 3,
          }
        },
      ],
      redirect: '/welcome',
    },

    {
      path: '/auth',
      name: 'Auth',
      component: () => import('../views/authView.vue'),
      meta: {
        index: 0, // 确保路由层级正确
        hideNavigation: true // 添加自定义元字段
      }
    },
  ],
});

router.beforeEach(async (to) => {
  const authStore = useAuthStore();

  // 需要认证的路由
  if (to.meta.requiresAuth && !authStore.token) {
    return '/login';
  }

  // 已登录时访问登录页跳转首页
  if (to.name === 'login' && authStore.token) {
    return '/';
  }

  // 获取用户信息
  if (authStore.token && !authStore.userInfo) {
    await authStore.fetchUserInfo();
  }
});

export default router
